package com.xwaiy.xwaiyrpc.server;

import com.xwaiy.xwaiyrpc.RpcApplication;
import com.xwaiy.xwaiyrpc.model.RpcRequest;
import com.xwaiy.xwaiyrpc.model.RpcResponse;
import com.xwaiy.xwaiyrpc.registry.LocalRegistry;
import com.xwaiy.xwaiyrpc.serializer.JdkSerializer;
import com.xwaiy.xwaiyrpc.serializer.Serializer;
import com.xwaiy.xwaiyrpc.serializer.SerializerFactory;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Http 请求处理
 * @Author Xwaiy
 * @Date 2025/8/20 17:39
 **/
public class HttpServerHandler implements Handler<HttpServerRequest> {
    @Override
    public void handle(HttpServerRequest request) {
        // 指定序列化器
        final Serializer serializer = SerializerFactory.getInstance(RpcApplication.getRpcConfig().getSerializer());

        // 日志
        System.out.println("接收请求："+request.method()+" "+request.uri());

        // 异步处理请求
        request.bodyHandler(body ->{
           byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try {
                rpcRequest = serializer.deserialize(bytes,RpcRequest.class);
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 构造响应结果对象
            RpcResponse rpcResponse = new RpcResponse();
            if(rpcRequest == null) {
                rpcResponse.setMsg("rpc请求为空");
                doResponse(request,rpcResponse,serializer);
                return;
            }

            try{
                // 获取需要调用的服务实现对象
                Object serviceImpl = LocalRegistry.getService(rpcRequest.getServiceName());
                Method method = serviceImpl.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
                Object result = method.invoke(serviceImpl, rpcRequest.getParams());
                // 封装结果
                rpcResponse.setData(result);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMsg("OK");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setMsg(e.getMessage());
                rpcResponse.setException(e);
            }
            // 响应
            doResponse(request, rpcResponse, serializer);
        });

    }

    /**
     * 响应
     * @param request
     * @param rpcResponse
     * @param serializer
     */
    void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse response = request.response().putHeader("content-type","application/json;charset=utf-8");
        try{
            // 序列化
            byte[] serialized = serializer.serialize(rpcResponse);
            response.end(Buffer.buffer(serialized));
        }catch (IOException e){
            e.printStackTrace();
            response.end(Buffer.buffer());
        }
    }
}
